﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using CGOnline.Server.Core;
using CGOnline.Server.Components;

namespace CGOnline.Server.UserLayer
{
    public class CGUser : UserBase, IComponentProbe
    {
        public CGUser(IUserChannel channel,UserConfig config)
        {
            //////////////////////////////
            if (channel == null)
                Component.Notify();
            //////////////////////////////

            UserChannel = channel;
            Config = config;
        }

        RoomBase _room;
        public override bool LeaveRoom()
        {
            if (_room != null)
            {
                if (_room.UserLeave(this))
                    return true;
            }
            return false;
        }

        public override bool AttendRoom(RoomBase room,object data)
        {
            if (room != null)
            {
                if (room.UserIn(this, data))
                {
                    _room = room;
                    _room.Broadcast += _room_Broadcast;
                    _room.StateChanged +=_room_StateChanged;
                    return true;
                }
            }
            return false;
        }

        protected bool ChannelSend(object sender,MyEventArgs eventargs)
        {
            if (UserChannel != null)
            {
                return UserChannel.UserEventNotify(new EventPack
                {
                    EventArgs = eventargs,
                    SenderTypeHash = sender.GetType().GetHashCode(),
                    SenderHash = sender.GetHashCode()
                });
            }
            return false;
        }

        void _room_StateChanged(object sender, StateEventArgs e)
        {
            if(GetState(USER_STATEGROUP)!=USER_STATEGROUP_OFFLINE)
                ChannelSend(sender, e);
        }

        void _room_Broadcast(object sender, RoomEventArgs e)
        {
            if (GetState(USER_STATEGROUP) != USER_STATEGROUP_OFFLINE)
                ChannelSend(sender, e);
        }

        public override bool SendMsg(Message msg)
        {
            if (_room != null)
            {
                return _room.UserSendMsg(this, msg);
            }
            return false;
        }

        DateTime _lastsynctime;
        public override List<Message> ReceiveMsgs()
        {
            if (_room != null)
            {
                var ret = _room.UserGetMsgs(this,_lastsynctime);
                _lastsynctime = DateTime.Now;
                return ret;
            }
            return null;
        }


        #region IComponentProbe Members

        public IComponentInner Component
        {
            set;
            get;
        }

        #endregion
    }
}
